﻿using System;
using System.Globalization;
using System.Web.UI;
using System.Web.UI.WebControls;
using mojoPortal.Business;
using mojoPortal.Business.WebHelpers;
using mojoPortal.Web.Framework;
using mojoPortal.Web;
using Resources;
using ud_Article.Business;
using System.Collections.Generic;
using System.Text;
using ud_Utilities;

namespace ud_Article.UI
{
    public partial class SearchResult : UserControl
    {
        #region Properties

        private int pageNumber = 1;
        private int totalPages = 1;
        protected string EditContentImage = WebConfigSettings.EditContentImage;
        protected string EditBlogAltText = "Edit";
        protected Double TimeOffset;
        private TimeZoneInfo timeZone;
        protected bool ShowGoogleMap = true;
        protected string FeedBackLabel = string.Empty;
        protected string GmapApiKey = string.Empty;
        protected bool EnableContentRating;
        private string DisqusSiteShortName = string.Empty;
        protected string disqusFlag = string.Empty;
        protected string IntenseDebateAccountId = string.Empty;
        protected bool ShowCommentCounts = true;
        protected string EditLinkText = ArticleResources.BlogEditEntryLink;
        protected string EditLinkTooltip = ArticleResources.BlogEditEntryLink;
        protected string EditLinkImageUrl = string.Empty;
        private mojoBasePage basePage;
        private Module module;
        protected ArticleSearchConfiguration config = new ArticleSearchConfiguration();

        private int pageId = -1;
        private int moduleId = -1;
        private string siteRoot = string.Empty;
        private string imageSiteRoot = string.Empty;
        private SiteSettings siteSettings;
        private int categoryId = -1;
        private int loadedModuleId = -1;
        private int loadedPageId = -1;
        private int searchModuleId = -1;
        private int searchCategoryId = -1;
        private int searchTypeId = -1;
        private string searchTerm = string.Empty;

        public int SearchModuleId
        {
            get { return searchModuleId; }
            set { searchModuleId = value; }
        }

        public int SearchCategoryId
        {
            get { return searchCategoryId; }
            set { searchCategoryId = value; }
        }

        public int SearchTypeId
        {
            get { return searchTypeId; }
            set { searchTypeId = value; }
        }

        public string SearchTerm
        {
            get { return searchTerm; }
            set { searchTerm = value; }
        }

        public int LoadedModuleID
        {
            get { return loadedModuleId; }
            set { loadedModuleId = value; }
        }

        public int LoadedPageId
        {
            get { return loadedPageId; }
            set { loadedPageId = value; }
        }

        public int PageId
        {
            get { return pageId; }
            set { pageId = value; }
        }

        public int ModuleId
        {
            get { return moduleId; }
            set { moduleId = value; }
        }

        public string SiteRoot
        {
            get { return siteRoot; }
            set { siteRoot = value; }
        }

        public string ImageSiteRoot
        {
            get { return imageSiteRoot; }
            set { imageSiteRoot = value; }
        }

        public ArticleSearchConfiguration Config
        {
            get { return config; }
            set { config = value; }
        }

        public bool IsEditable { get; set; }

        public int CategoryID
        {
            get { return categoryId; }
            set { categoryId = value; }
        }

        #endregion


        protected override void OnInit(EventArgs e)
        {

            base.OnInit(e);
            Load += Page_Load;
            EnableViewState = false;
        }

        protected virtual void Page_Load(object sender, EventArgs e)
        {
            LoadSettings();

#if !MONO
            if (!(Page is mojoPortal.Web.UI.Pages.MyPage))
            {
                SetupRssLink();
            }
#endif

            PopulateLabels();
            if (!Page.IsPostBack)
            {
                PopulateControls();
            }

        }

        private void PopulateControls()
        {
            BindBlogs();
        }

        private void BindBlogs()
        {
            DBArticleLinq repository = new DBArticleLinq();
            List<Business.ud_Article> result = new List<Business.ud_Article>();
            switch (searchTypeId)
            {
                case 1:
                    result = repository.SearchByTitle(siteSettings.SiteId, searchModuleId, searchCategoryId, searchTerm);
                    break;
                case 2:
                    result = repository.SearchByContent(siteSettings.SiteId, searchModuleId, searchCategoryId, searchTerm);
                    break;
                case 0:
                    result = repository.Search(siteSettings.SiteId, searchModuleId, searchCategoryId, searchTerm);
                    break;
            }
            totalPages = result.Count / config.PageSize;
            if (result.Count > config.PageSize)
            {
                result = result.GetRange((pageNumber - 1) * config.PageSize, config.PageSize);
            }
            rptBlogs.DataSource = result;
            rptBlogs.DataBind();
            string pageUrl = SiteRoot + "/ArticleLoader/SearchResult.aspx"
               + "?pageid=" + pageId.ToInvariantString()
               + "&amp;mid=" + moduleId.ToInvariantString()
               + "&amp;sm=" + searchModuleId.ToInvariantString()
               + "&amp;sc=" + searchCategoryId.ToInvariantString()
               + "&amp;st=" + searchTypeId.ToInvariantString()
               + "&amp;pagenumber={0}";
            pgr.PageURLFormat = pageUrl;
            pgr.ShowFirstLast = true;
            pgr.PageSize = config.PageSize;
            pgr.PageCount = totalPages;
            pgr.CurrentIndex = pageNumber;
            pnlBlogPager.Visible = (totalPages > 1) && config.ShowPager;
        }

        //void pgr_Command(object sender, CommandEventArgs e)
        //{
        //    pageNumber = Convert.ToInt32(e.CommandArgument);
        //    pgr.CurrentIndex = pageNumber;
        //    PopulateControls();
        //    updBlog.Update();
        //}

        protected virtual void PopulateLabels()
        {
            EditBlogAltText = ArticleResources.EditImageAltText;
            FeedBackLabel = ArticleResources.BlogFeedbackLabel;

            mojoBasePage mojoBasePage = Page as mojoBasePage;
            if (mojoBasePage != null)
            {
                if (!mojoBasePage.UseTextLinksForFeatureSettings)
                {
                    EditLinkImageUrl = ImageSiteRoot + "/Data/SiteImages/" + EditContentImage;
                }
            }
        }
        
        protected string FormatBlogEntry(string blogHtml, string excerpt, string url, int itemId)
        {
            if (config.UseExcerpt)
            {
                if ((excerpt.Length > 0) && (excerpt != "<p>&#160;</p>"))
                {
                    return excerpt + config.ExcerptSuffix + " <a href='" + FormatBlogUrl(url, itemId) + "' class='morelink'>" + config.MoreLinkText + "</a><div>&nbsp;</div>";
                }
                blogHtml = SecurityHelper.RemoveMarkup(blogHtml);
                if (blogHtml.Length > config.ExcerptLength)
                {

                    string result = UIHelper.CreateExcerpt(blogHtml, config.ExcerptLength, config.ExcerptSuffix);
                    result += " <div class='morelink-wrapper'><div class='l'></div><div class='m'><a href='" + FormatBlogTitleUrl(url, itemId) + "' class='morelink'>" + config.MoreLinkText + "</a></div><div class='r'></div></div><div class='clear'></div>";
                    return result;
                }

            }

            return blogHtml;
        }

        protected string FormatPostAuthor(string userGuid)
        {
            return ArticleUtils.FormatPostAuthor(userGuid, config);
        }

        protected string FormatBlogDate(DateTime startDate)
        {
            return ArticleUtils.FormatBlogDate(startDate, config, timeZone, TimeOffset);
        }

        protected string FormatBlogUrl(string itemUrl, int itemId)
        {
            if (itemUrl.Length > 0)
                return SiteRoot + itemUrl.Replace("~", string.Empty) + disqusFlag;

            return SiteRoot + "/Article/ViewPost.aspx?pageid=" + PageId.ToInvariantString()
                + "&ItemID=" + itemId.ToInvariantString()
                + "&mid=" + ModuleId.ToInvariantString()
                + disqusFlag;

        }

        protected string FormatBlogTitleUrl(string itemUrl, int itemId)
        {
            if (itemUrl.Length > 0)
                return SiteRoot + itemUrl.Replace("~", string.Empty);

            return SiteRoot + "/Article/ViewPost.aspx?pageid=" + PageId.ToInvariantString()
                + "&ItemID=" + itemId.ToInvariantString()
                + "&mid=" + ModuleId.ToInvariantString();

        }

        protected string FormatBlogTitle(string title, int maxChars)
        {
            if (title.Length > maxChars)
            {
                title = title.Remove(maxChars);
                title += "...";
            }
            return title;
        }

        protected string FormatTooltip(string title, string content)
        {
            string result;
            if (config.UseTooltipSettings)
            {
                if (content.Length > config.TooltipMaxCharSettings)
                {
                    content = UIHelper.CreateExcerpt(content, config.TooltipMaxCharSettings, "...");
                }
                result = "<div class='tooltip'><div class='title-l'></div><div class='title-m'>" + title + "</div><div class='title-r'></div><div class='body'>" + content + "</div></div>";
            }
            else
            {
                result = title;
            }
            return result;
        }


        private string GetRssUrl()
        {
            if (config.FeedburnerFeedUrl.Length > 0) return config.FeedburnerFeedUrl;
            return SiteRoot + "/blog" + ModuleId.ToInvariantString() + "rss.aspx";
        }

        protected virtual void LoadSettings()
        {
            SetJQueryScript();
            siteSettings = CacheHelper.GetCurrentSiteSettings();
            TimeOffset = SiteUtils.GetUserTimeOffset();
            timeZone = SiteUtils.GetUserTimeZone();
            GmapApiKey = SiteUtils.GetGmapApiKey();
            pageNumber = WebUtils.ParseInt32FromQueryString("pagenumber", pageNumber);

            if (Page is mojoBasePage)
            {
                basePage = Page as mojoBasePage;
                module = basePage.GetModule(moduleId);
            }

            if ((config.UseExcerpt) && (!config.GoogleMapIncludeWithExcerpt)) { ShowGoogleMap = false; }

            EnableContentRating = config.EnableContentRating;
            if (config.UseExcerpt) { EnableContentRating = false; }

            DisqusSiteShortName = config.DisqusSiteShortName.Length > 0
                                      ? config.DisqusSiteShortName
                                      : siteSettings.DisqusSiteShortName;

            IntenseDebateAccountId = config.IntenseDebateAccountId.Length > 0 ? config.IntenseDebateAccountId : siteSettings.IntenseDebateAccountId;

            if (config.AllowComments)
            {
                if ((DisqusSiteShortName.Length > 0) && (config.CommentSystem == "disqus"))
                {
                    disqusFlag = "#disqus_thread";
                    disqus.SiteShortName = DisqusSiteShortName;
                    disqus.RenderCommentCountScript = true;

                }

                if ((IntenseDebateAccountId.Length > 0) && (config.CommentSystem == "intensedebate"))
                {
                    ShowCommentCounts = false;
                }
            }


            if (!config.NavigationOnRight)
            {
                divblog.CssClass = "blogcenter-leftnav";

            }
            if (config.Copyright.Length > 0)
            {
                lblCopyright.Text = config.Copyright;
            }

            divblog.CssClass = "blogcenter-nonav";
            if (IsEditable)
            {
                Article.CountOfDrafts(ModuleId);
            }
        }

        private void SetJQueryScript()
        {
            if (config.AutoScrollSetting || config.UseTooltipSettings)
            {
                ltrScript.Text = @"<script src='/ClientScript/jqmojo/jquery.tools.min.js' type='text/javascript'></script>";
                ltrAutoScrollCssSetup.Text = string.Empty;
            }
            if (config.AutoScrollSetting)
            {
                if (config.AutoScrollVerticalSetting)
                {
                    ltrAutoScrollCssSetup.Text += @"<style type='text/css'>"
                        + @".scrollable" + ModuleId + @"{"
                        + @"position:relative; overflow:hidden; float:left;"
                        + @"width:" + config.AutoScrollWidthWrapperSetting + @";"
                        + @"height:" + config.AutoScrollHeightWrapperSetting + @";}"
                        + @".scrollable" + ModuleId + @" .items{"
                        + @"height:20000em; position:absolute;}"
                        + @"</style>";
                }
                else
                {
                    ltrAutoScrollCssSetup.Text += @"<style type='text/css'>"
                        + @".scrollable" + ModuleId + @"{"
                        + @"position:relative; overflow:hidden; float:left;"
                        + @"width:" + config.AutoScrollWidthWrapperSetting + @";"
                        + @"height:" + config.AutoScrollHeightWrapperSetting + @";}"
                        + @".scrollable" + ModuleId + @" .items{"
                        + @"width:20000em; position:absolute;}"
                        + @".scrollable" + ModuleId + @" .items div{"
                        + @"float: left;}"
                        + @"</style>";
                }
                pnlScrollable.CssClass = "panel-scroll scrollable" + ModuleId;
                ltrScript.Text += @"<script type='text/javascript'>$(document).ready(function(){"
                                    + @"$('.scrollable" + ModuleId + @"').scrollable({"
                                    + @"circular: " + config.AutoScrollCircularSetting.ToString().ToLower()
                                    + @", speed: " + config.AutoScrollSpeedSetting
                                    + @", easing: '" + config.AutoScrollEasingSetting + @"'"
                                    + @", steps: " + config.AutoScrollItemsSetting
                                    + @", vertical: " + config.AutoScrollVerticalSetting.ToString().ToLower()
                                    + @"}).autoscroll(" + config.AutoScrollTimeSetting + @");});</script>";
            }
            if (config.UseTooltipSettings)
            {

                ltrScript.Text += @"<script type='text/javascript'>$(document).ready(function(){"
                                    + @"$('." + config.OtherArticlesCssClass + @" > div > div > a[title]').tooltip({"
                                    + @"opacity: 1"
                                    + @",effect: '" + config.TooltipEffectSettings + @"'"
                                    + @", delay: '" + config.TooltipDelaySettings + @"'"
                                    + @", tipClass: '" + config.UseTooltipCssSettings + @"'"
                                    + @"}).dynamic({ bottom: { direction: 'down', bounce: true } });;});</script>";
            }
        }

        protected virtual void SetupRssLink()
        {
            if (WebConfigSettings.DisableBlogRssMetaLink) { return; }

            if (module != null)
            {
                if (Page.Master != null)
                {
                    Control head = Page.Master.FindControl("Head1");
                    if (head != null)
                    {

                        Literal rssLink = new Literal
                                              {
                                                  Text =
                                                      @"<link rel=""alternate"" type=""application/rss+xml"" title="""
                                                      + module.ModuleTitle + @""" href="""
                                                      + GetRssUrl() + @""" />"
                                              };

                        head.Controls.Add(rssLink);

                    }

                }
            }

        }
        public string FormatDialogScript(string mID, string itemID)
        {
            StringBuilder sb = new StringBuilder();
            sb.Append("<script type='text/javascript'>");
            sb.Append("$(document).ready(function(){");
            sb.Append("$('.img" + mID + itemID + "').click(function(){");

            sb.Append("$('." + mID + itemID + "').dialog('option', 'width', 'auto');");
            sb.Append("$('." + mID + itemID + "').dialog('open'); return false;");

            sb.Append("});");
            sb.Append("});");
            sb.Append("</script>");
            return sb.ToString();
        }

        public string FormatImageDialog(string imageUrl)
        {
            string result = imageUrl;
            if (result.Contains("."))
            {
                result = result.Insert(imageUrl.LastIndexOf("."), "_t");
            }
            return result;
        }
    }
}